/**
 * Created by 赵栋 on 2017/4/6.
 */
var express = require('express');
var router = express.Router();
var config = require('../lib/config/config').config;
var qs = require('querystring');
var logger = require('../lib/log4js/log4js').logger('apiLog');
var myRet = require('../lib/common/common').myReturn;
var http = require('http');

function _request(url,method,data,cb,ctype){

    if(ctype === undefined)
        ctype = 'text/xml';

    var opt = {
        host:config.elasticsearch.host,
        port:config.elasticsearch.port,
        method: method,
        path: url,
        headers: {
            'Content-Type': ctype,
            'Content-Length': data.length
        }
    };

    var request =http.request(opt,function(response){
        var postData = "";
        response.addListener("data", function (postDataChunk) {
            postData += postDataChunk;
        });
        response.addListener("end", function () {
            //res.send(postData);
            cb(response,postData);
        });
    });
    request.write(data);
    request.end();
}
function _request1(url,method,data,cb,ctype){

    if(ctype === undefined)
        ctype = 'text/xml';

    var opt = {
        host:config.kubernetes.host,
        port:config.kubernetes.port,
        method: method,
        path: url,
        headers: {
            'Content-Type': ctype,
            'Content-Length': data.length
        }
    };

    var request =http.request(opt,function(response){
        var postData = "";
        response.addListener("data", function (postDataChunk) {
            postData += postDataChunk;
        });
        response.addListener("end", function () {
            //res.send(postData);
            cb(response,postData);
        });
    });
    request.write(data);
    request.end();
}
function formmateTime(date) {
    var d=new Date(Date.parse(date.replace(/-/g,"/")));
    var d_s=d.getTime();
    d.setTime(d_s-1000*60*60*8);
    var data=d.toISOString().slice(0,10);
    var dat=data+'T'+zero(d.getHours())+':'+zero(d.getMinutes())+':'+zero(d.getSeconds());
    return dat;
}
function zero(time) {
    if(time.toString().length<2){
        return 0+time.toString();
    }else{
        return time.toString();
    }
}
function formmateTime1(date) {
    var d=new Date(Date.parse(date.replace(/-/g,"/")));
    var d_s=d.getTime();
    d.setTime(d_s+1000*60*60*16);
    var data=d.toISOString().slice(0,10);
    var dat=data+'T'+zero(d.getHours())+':'+zero(d.getMinutes())+':'+zero(d.getSeconds());
    return dat;
}
router.post('/getLog', function (req,res,next) {
    var _data=req.body;
    var _query={};
    var query={};
    query.filtered={};
    query.filtered.query={};
    query.filtered.query.bool={};
    query.filtered.query.bool.must=[];
    query.filtered.query.bool.must[0]={};
    query.filtered.query.bool.must[0].match={};
    query.filtered.query.bool.must[0].match.tag='';
    if(_data.key){
        query.filtered.query.bool.must[1]={};
        query.filtered.query.bool.must[1].match={};
        query.filtered.query.bool.must[1].match.log='';
        query.filtered.query.bool.must[1].match.log = _data.key;
    }
    query.filtered.filter={};
    query.filtered.filter.range={};
    query.filtered.filter.range["@timestamp"]={};
    if(_data.st){
        query.filtered.filter.range["@timestamp"].gt='';
        var st=formmateTime(_data.st);
        query.filtered.filter.range["@timestamp"].gt=st;
    }
    if(_data.ed){
        query.filtered.filter.range["@timestamp"].lt='';
        var ed=formmateTime1(_data.ed);
        query.filtered.filter.range["@timestamp"].lt=ed;
    }
    var time={};
    time.order="desc";
    var sort={};
    sort["@timestamp"]=time;
    var url='/_search';
    var url1='/api/v1/namespaces/'+req.username+'/pods/'+_data.po;
    _request1(url1,'GET','',function (response,data) {
        if(response.statusCode=== 200){
            var json=JSON.parse(data);
            var containerid=json.status.containerStatuses[0].containerID;
            var tagname=containerid.split('//')[1];
            if(config.elasticsearch.json) {
                tagname=tagname + '-json.log';
            }
            query.filtered.query.bool.must[0].match.tag=tagname;
            _query.query=query;
            _query.size=50;
            _query.sort=sort;
            var param=JSON.stringify(_query);
            _request(url, 'POST',param, function (respons, log) {
                if (respons.statusCode === 200) {
                    //cheerio.load(data);
                    var lg=JSON.parse(log);
                    var logs=[];
                    for(var i=0;i<lg.hits.hits.length;i++){
                       logs.push(lg.hits.hits[i]._source.log);
                    }
                    var logsr=logs.reverse();
                    res.send(logsr);
                }  else{
                    res.send(myRet(false));
                }
            });
        }else{
            res.send(myRet(false));
        }
    });
});
module.exports = router;